package cn.ysbd.datafactory.engine.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * @Author: YinHeng
 * @Description:
 * @DateTime: 2022/10/25 16:53
 */
public class URLConnectionHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(URLConnectionHelper.class.getName());


    public static String sendRequest(String urlStr) {

        HttpURLConnection con;

        BufferedReader buffer;
        StringBuilder resultBuffer;

        try {
            URL url = new URL(urlStr);
            con = (HttpURLConnection) url.openConnection();

            //设置请求需要返回的数据类型和字符集类型
            con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
            con.setConnectTimeout(30000);
            con.setReadTimeout(30000);
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);

            LOGGER.debug("log-url:" + urlStr + " code:" + con.getResponseCode());
            //得到响应流
            InputStream inputStream = con.getInputStream();
            //将响应流转换成字符串
            resultBuffer = new StringBuilder();
            String line;
            buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = buffer.readLine()) != null) {
                resultBuffer.append(line);
            }
            return resultBuffer.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}
